package com.whsxt.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whsxt.domain.UserAddr;
import com.whsxt.mapper.UserAddrMapper;
import com.whsxt.service.UserAddrService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-03-21 16:50
 * @Description: ${Description}
 */
@Service
@CacheConfig(cacheNames = "com.whsxt.service.impl.UserAddrServiceImpl")
@Slf4j
public class UserAddrServiceImpl extends ServiceImpl<UserAddrMapper, UserAddr> implements UserAddrService {


    @Autowired
    private UserAddrMapper userAddrMapper;


    /**
     * 查询用户收货地址
     *
     * @param openId
     * @return
     */
    @Override
    @Cacheable(key = "#openId")
    public List<UserAddr> findUserAddrByOpenId(String openId) {
        return userAddrMapper.selectList(new LambdaQueryWrapper<UserAddr>()
                .eq(UserAddr::getUserId, openId)
                .eq(UserAddr::getStatus, 1)
        );
    }


    /**
     * 新增收货地址
     *
     * @param userAddr
     * @return
     */
    @Override
    @CacheEvict(key = "#userAddr.userId")
    public boolean save(UserAddr userAddr) {
        log.info("新增用户收货地址：{}", JSON.toJSONString(userAddr));
        userAddr.setCreateTime(new Date());
        userAddr.setStatus(1);
        userAddr.setUpdateTime(new Date());
        userAddr.setVersion(0);
        //如果用户之前没有收货地址，新增的这一条就是默认收货地址
        Integer count = userAddrMapper.selectCount(new LambdaQueryWrapper<UserAddr>()
                .eq(UserAddr::getUserId, userAddr.getUserId())
        );
        if (count == 0) {
            userAddr.setCommonAddr(1);
        }
        int insert = userAddrMapper.insert(userAddr);

        return insert > 0;
    }


    /**
     * 修改用户默认收货地址
     *
     * @param openId
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(key = "#openId")
    public void changeDefaultAddr(String openId, Long id) {
        log.info("修改默认地址，用户id：{}，地址id：{}", openId, id);
        //查询之前的默认地址
        UserAddr oldAddr = userAddrMapper.selectOne(new LambdaQueryWrapper<UserAddr>()
                .eq(UserAddr::getUserId, openId)
                .eq(UserAddr::getCommonAddr, 1)
        );

        if (oldAddr != null) {
            oldAddr.setCommonAddr(0);
            userAddrMapper.updateById(oldAddr);
        }

        UserAddr userAddr = userAddrMapper.selectById(id);
        if (userAddr == null) {
            throw new RuntimeException("地址不存在");
        }
        userAddr.setAddrId(id);
        userAddr.setCommonAddr(1);
        userAddrMapper.updateById(userAddr);
    }
}
